<script setup lang="ts">
  import { defineProps, reactive, ref, watch } from 'vue';
  import { useBooleanStore } from '@/store';
  import { Notification } from '@arco-design/web-vue';
  import { queryAOByToolCode, queryOut, callTray } from '@/api/les';

  const props = defineProps<{
    tableData: any;
    detailData: any;
  }>();
  const booleanStore = useBooleanStore();
  const hStyle = ref({
    'background-color': booleanStore.color,
    'border-radius': booleanStore.borderRadius,
  });
  // 日计划数据头
  const aoColumns: any[] = [
    {
      title: '序号',
      dataIndex: 'index',
      slotName: 'index',
      align: 'center',
      width: '60',
    },
    {
      title: '托盘号',
      dataIndex: 'toolCode',
      // slotName: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '180',
    },
    {
      title: 'AO编码',
      dataIndex: 'aoCode',
      width: '180',
    },
    // {
    //   title: 'AO条码',
    //   dataIndex: 'aoBarcode',
    //   sortable: {
    //     sortDirections: ['ascend', 'descend'],
    //   },
    //   width: '180',
    // },

    {
      title: 'AO站位',
      dataIndex: 'station',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '160',
    },
    {
      title: 'AO数量',
      dataIndex: 'aoNum',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '100',
    },

    {
      title: '要求时间',
      dataIndex: 'dailyTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '180',
    },
    {
      title: '任务状态',
      dataIndex: 'taskStatus',
      slotName: 'taskStatus',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '180',
    },
    // {
    //   title: '分拣台IP',
    //   dataIndex: 'sortingIp',
    //   sortable: {
    //     sortDirections: ['ascend', 'descend'],
    //   },
    //   width: '180',
    // },
    {
      title: '批次',
      dataIndex: 'batchNo',
      // slotName: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '140',
    },
    {
      title: '架次',
      dataIndex: 'startPlaneNo',
      // slotName: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '140',
    },
    {
      title: '机型',
      dataIndex: 'productCode',
      // slotName: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '180',
    },
  ];
  // 配送任务数据头
  const detailColumns: any[] = [
    {
      title: '序号',
      dataIndex: 'index',
      slotName: 'index',
      align: 'center',
      fixed: 'left',
      width: '60',
    },
    {
      title: '配送任务编号',
      dataIndex: 'lesPlanMainCode',
      width: '180',
    },
    {
      title: 'AO站位',
      dataIndex: 'station',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '180',
    },
    {
      title: '托盘号',
      dataIndex: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '180',
    },
    {
      title: '要求时间',
      dataIndex: 'requiredTime',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '180',
    },
    {
      title: '任务状态',
      dataIndex: 'planState',
      slotName: 'planState',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '180',
    },
    {
      title: '批次',
      dataIndex: 'batchNo',
      // slotName: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '100',
    },
    {
      title: '架次',
      dataIndex: 'startPlaneNo',
      // slotName: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '100',
    },
    {
      title: '机型',
      dataIndex: 'product',
      // slotName: 'toolCode',
      sortable: {
        sortDirections: ['ascend', 'descend'],
      },
      width: '120',
    },
    {
      title: '操作',
      dataIndex: 'action',
      slotName: 'action',
      align: 'center',
      fixed: 'right',
      width: '100',
    },
  ];

  // 创建一个响应式的本地副本
  const localTableData = ref<any[]>([]);
  const detailList = ref<any[]>([]);

  // 数据库一共有多少条
  const total = ref<number>(0);
  const pageNum = ref<number>(1);
  const pageSize = ref<number>(10);
  const detailTotal = ref<number>(0);
  const detailPageNum = ref<number>(1);
  const detailPageSize = ref<number>(10);

  const selectedKeys = ref<string[]>();
  const selectedRow = ref<any[]>([]);
  const rowSelection = reactive({
    type: 'checkbox' as const,
    showCheckedAll: true,
    onlyCurrent: false,
  });
  const expandedRowKeys = ref<any[]>([]);
  function handleExpand(expanded: any, record: { lesPlanMainId: any }) {
    if (expanded) {
      // 展开时，只保留当前行的key
      expandedRowKeys.value = [record.lesPlanMainId];
    } else {
      // 收起时清空
      expandedRowKeys.value = [];
    }
  }
  const expandableConfig = reactive({
    expandedRowKeys: expandedRowKeys.value,
    onExpand: handleExpand,
  });

  // 监听props.tableData的变化，并更新本地副本
  watch(
    () => props.tableData,
    () => {
      localTableData.value = props.tableData?.responseBody?.records || [];
      total.value = props.tableData?.responseBody?.total || 0;
    },
    { immediate: true }
  );
  watch(
    () => props.detailData,
    () => {
      detailList.value = props.detailData?.responseBody?.records || [];
      detailTotal.value = props.detailData?.responseBody?.total || 0;
    },
    { immediate: true }
  );

  function change(e: any) {
    pageNum.value = e;
  }
  function detailChange(e: any) {
    detailPageNum.value = e;
  }
  function changeSize(e: any) {
    pageSize.value = e;
  }
  function detailChangeSize(e: any) {
    detailPageSize.value = e;
  }

  // 监听页面变化
  watch([pageNum, pageSize], () => {
    booleanStore.setPage(pageNum.value, pageSize.value, 54);
  });

  watch([detailPageNum, detailPageSize], () => {
    booleanStore.setPage(detailPageNum.value, detailPageSize.value, 55);
  });

  const rowInfo = ref<any[]>([]);
  const toolCodeAoList = ref<any[]>([]);

  async function findAOByToolCode(record: any) {
    const data = await queryAOByToolCode(record);
    if (data.retCode === '200') {
      toolCodeAoList.value = data.responseBody;
      const isStart = toolCodeAoList.value.every((item: any) => {
        // 如果 item.isDailyPlan 为 true，返回 true
        return item.isDailyPlan;
      });
      if (!isStart) {
        Notification.error({
          title: '失败',
          content: '当前托盘需要拆包',
          closable: true,
        });
        return false;
      }
      return true;
    }
    Notification.error({
      title: '失败',
      content: data.message,
      closable: true,
    });
    return false;
  }

  async function startPlan() {
    if (!selectedRow.value || selectedRow.value.length === 0) {
      Notification.error({
        title: '失败',
        content: '请选择一条数据',
        closable: true,
      });
      return;
    }
    // 判断rowInfo中的AO站位全部一致
    if (
      selectedRow.value.length > 1 &&
      selectedRow.value.some(
        (item) => item.station !== selectedRow.value[0].station
      )
    ) {
      Notification.error({
        title: '失败',
        content: 'AO站位不一致',
        closable: true,
      });
      return;
    }

    // 判断所有托盘都是未下发
    if (selectedRow.value.some((item) => item.taskStatus !== '00')) {
      Notification.error({
        title: '失败',
        content: '存在已下发任务的托盘，请重新选择',
        closable: true,
      });
      return;
    }

    // 使用 Promise.all 并行处理每个 row 的 findAOByToolCode 请求
    const results = await Promise.all(
      selectedRow.value.map(async (row) => {
        const isPass = await findAOByToolCode(row.children);
        if (!isPass) return false;
        return true;
      })
    );

    // 如果有任何一个请求失败，则停止后续操作
    if (results.some((result) => result === false)) {
      return;
    }

    rowInfo.value = selectedRow.value;
    selectedKeys.value = [];
    selectedRow.value = [];

    const data = await queryOut(rowInfo.value);
    if (data.retCode === '200') {
      booleanStore.watchUpdate(29);
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
    rowInfo.value = [];
  }

  // 呼叫托盘
  async function callTrays(record: any) {
    const executeDatas = ref<any[]>([]);
    const notOutDatas = ref<any[]>([]);
    // 查询其他已开始的任务
    executeDatas.value = detailList.value.filter(
      (item) =>
        record.lesPlanMainId !== item.lesPlanMainId && item.planState !== 0
    );
    // 循环所有执行中的任务，判断任务的子数据中是否有未出库的
    executeDatas.value.forEach((element) => {
      // 查询出每个任务的子数据中所有未出库的托盘
      const notOutData = element.children.filter(
        (item: any) => item.planState === 0
      );
      notOutDatas.value.push(...notOutData);
    });
    // 判断是否有未出库的托盘有就失败
    if (notOutDatas.value.length > 0) {
      Notification.warning({
        title: '警告',
        content: '已执行任务还存在未出库的托盘，请等待托盘出库',
        closable: true,
      });
      return;
    }
    const toolCodes = record.children.map((item: any) => item.toolCode);
    const data = await callTray({
      lesPlanMainId: record.lesPlanMainId,
      toolCodes,
    });
    if (data.retCode === '200') {
      booleanStore.watchUpdate(30);
      Notification.success({
        title: '成功',
        content: data.message,
        closable: true,
      });
    } else {
      Notification.error({
        title: '失败',
        content: data.message,
        closable: true,
      });
    }
  }

  watch(selectedKeys, (newKeys) => {
    if (newKeys && newKeys.length > 0) {
      selectedRow.value = localTableData.value.filter((row) =>
        newKeys.includes(row.toolCode)
      );
    } else selectedRow.value = [];
  });
</script>

<template>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">配送日计划</div>
    </template>
    <template #extra>
      <a-button type="primary" status="success" @click="startPlan"
        >生成任务</a-button
      >
    </template>

    <a-table
      :stripe="true"
      class="top-table"
      :pagination="false"
      :columns="aoColumns"
      :data="localTableData"
      :scroll="{ y: 400 }"
      style="height: 250px; margin-top: 8px"
      v-model:selected-keys="selectedKeys"
      :row-selection="rowSelection"
      row-key="toolCode"
    >
      <template #index="{ record }">
        <span v-if="record.children">{{
          localTableData.indexOf(record) + 1
        }}</span>
      </template>
      <template #taskStatus="{ record }">{{
        record.taskStatus === '00' ? '未下发' : '已下发'
      }}</template>
    </a-table>
    <div class="page-position">
      <a-pagination
        :total="total"
        :current="pageNum"
        :page-size="pageSize"
        show-total
        show-jumper
        show-page-size
        @change="change"
        @update:pageSize="changeSize"
        :expandable="expandableConfig"
        :expanded-row-keys="expandedRowKeys"
      />
    </div>
  </a-card>
  <a-card :header-style="hStyle" :bordered="false">
    <template #title>
      <div class="font">配送任务</div>
    </template>
    <a-table
      :stripe="true"
      :pagination="false"
      class="top-table"
      :columns="detailColumns"
      :data="detailList"
      :scroll="{ y: 400 }"
      :indent-size="15"
      style="height: 250px"
    >
      <template #index="{ record }">
        <!-- 只对主数据显示序号 -->
        <span v-if="record.children">{{ detailList.indexOf(record) + 1 }}</span>
      </template>
      <template #planState="{ record }">
        <span v-if="record.children">{{
          record.planState === 0
            ? '未开始'
            : record.planState === 1
            ? '执行中'
            : record.planState === 2
            ? '托盘装车'
            : record.planState === 3
            ? '待配送'
            : record.planState === 4
            ? '已配送'
            : ''
        }}</span>
        <span v-else>{{
          record.planState === 0
            ? '未出库'
            : record.planState === 1
            ? '准备出库'
            : record.planState === 2
            ? '已出库'
            : record.planState === 3
            ? '已装车'
            : record.planState === 4
            ? '已配送'
            : ''
        }}</span>
      </template>
      <template #action="{ record }">
        <a-popconfirm
          v-if="record.children"
          content="确定呼叫托盘?"
          ok-text="确认"
          cancel-text="取消"
          @ok="callTrays(record)"
        >
          <a-button type="text" class="font-color">呼叫托盘</a-button>
        </a-popconfirm>
      </template>
    </a-table>
    <div class="page-position">
      <a-pagination
        :total="detailTotal"
        :current="detailPageNum"
        :page-size="detailPageSize"
        show-total
        show-jumper
        show-page-size
        @change="detailChange"
        @update:pageSize="detailChangeSize"
      />
    </div>
  </a-card>
</template>

<style scoped>
  .top-table {
    white-space: nowrap;
  }
  .page-position {
    margin-top: 20px;
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .font {
    font-size: 20px;
    color: black;
    font-family: system-ui, -apple-system, BlinkMacSystemFont, 'Segoe UI',
      Roboto, Oxygen, Ubuntu, Cantarell, 'Open Sans', 'Helvetica Neue',
      sans-serif;
  }
</style>
